package com.zfp.sys.controller;


import com.zfp.core.plugins.page.Page;
import com.zfp.core.utils.ExcelPoi;
import com.zfp.core.utils.Md5Util;
import com.zfp.sys.entity.SysMenu;
import com.zfp.sys.entity.SysUser;
import com.zfp.sys.service.SysMenuService;
import com.zfp.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("sys/sysUser/")
public class SysUserController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysMenuService sysMenuService;
	
	@RequestMapping("pageList")
	public String pageList(Model model,SysUser sysUser,Page<SysUser> page){
		if (page.getShowCount() == 20) {
			page.setShowCount(13); // 初始页面每页几行自定义
		}
		page=sysUserService.pageList(page, sysUser);
		model.addAttribute("page", page);
		model.addAttribute("sysUser", sysUser);
		return "sys/user_list";
	}
	@RequestMapping("checkLoginNameExist")
	@ResponseBody
	public String checkLoginNameExist(String loginName){
		SysUser sysUser =new SysUser();
		sysUser.setLoginName(loginName);
		List<SysUser> list = sysUserService.findAllList(sysUser);
		String result = "no";
		if(list.size()>0){
			result = "existUser";
		}
		return result;
	}
	@RequestMapping("save")
	public void save(PrintWriter out,SysUser sysUser){
		//System.out.println(sysUser.getUserId());
		Boolean b = sysUserService.save(sysUser);
		//System.out.println(b);
		out.print(b);
		
	}

	@RequestMapping("delete")
	public void delete(PrintWriter out,String id){
		Boolean b = sysUserService.deleteById(id);
		out.print(b);
		out.close();
	}
	
	@RequestMapping("turn")
	public String turn(String userId,Model model){
		if(userId != null && userId != ""){
			SysUser sysUser=sysUserService.getById("SysUser.getById", userId);
			model.addAttribute("user",sysUser);
		}
		return "sys/user_save"; 
	}

	/**
	 * 进入用户角色分配界面
	 * @param model
	 *
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("userRoleEdit")
	public String userRoleEdit(Model model, String id,HttpSession session) {
		//除了超级用户（角色id为1的用户系统认为是超级用户）其他的用户只能看到自己新建的递归用户
		SysUser sysUserSession = (SysUser) session.getAttribute("sessionUser");
		Map<String,String> roleSelectMap =  sysUserService.getRoleSelectMap(Long.parseLong(id),sysUserSession);
		model.addAttribute("select1", roleSelectMap.get("select1"));
		model.addAttribute("select2", roleSelectMap.get("select2"));
		model.addAttribute("id", id);
		return "sys/sysUser_editRole";
	}

	/**用户角色保存
	 * roleMenuSave
	 * @return
	 */
	@RequestMapping("saveUserRole")
	public void saveUserRole(PrintWriter out, String userId,String roleIds,HttpSession session) {
		SysUser sysUser = (SysUser) session.getAttribute("sessionUser");
		sysUserService.saveUserRoleTr(userId,roleIds,sysUser.getUserId());
		out.write("success");
		out.close();
	}
	@RequestMapping("initialize")
	@ResponseBody
	public String initialize(SysUser sysUser,HttpSession session){
		SysUser loginUser = (SysUser) session.getAttribute("sessionUser");
		String msg = "";
		Long loginId = loginUser.getUserId();
		int flag = 0;
		if(loginId != null){
			if(loginId != 1){
				msg = "no";
			}else{
				sysUser.setPassword(Md5Util.md5L32("00000000"));
				flag = sysUserService.update("SysUser.initialize",sysUser);
				msg = flag >= 1?"success":"fail";
			}
		}
		return msg;


	}


	@RequestMapping("exportUser")
	public void exportUser(HttpServletRequest request, HttpServletResponse response,SysUser sysUser){
//		System.out.println(sysUser.getLoginName()+"------"+sysUser.getUserName());
		List<SysUser> dataList = sysUserService.findAllList(sysUser);  
        try {   
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
	        response.setHeader("Content-disposition", "attachment;filename="+new String("用户表.xls".getBytes("GBK"), "ISO8859-1")); 
			OutputStream out = response.getOutputStream();
			new ExcelPoi().exportUser(dataList, out, "用户表");
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("toLogin")
	public String toLogin(Model model, HttpSession session,HttpServletRequest request,String isfront){
		SysUser sysUser = (SysUser)session.getAttribute("sessionUser");
		model.addAttribute("isfront",isfront);
		if(sysUser != null){
			return "redirect:/sys/sysUser/main.do";
		}else{
			return "sys/login";
		}
	}

	@RequestMapping("login")
	public void login(HttpSession session,PrintWriter out,String loginName,String password){
		String loginResult = "";
		SysUser sysUser = sysUserService.getLoginUser(loginName,password);
		if(sysUser != null){
			session.setAttribute("sessionUser",sysUser);
			loginResult = "success";
		}else{
			loginResult = "fail";
		}
		out.write(loginResult);
		out.close();

	}
	@RequestMapping("loginOut")
	public String loginOut(HttpSession session){
        session.removeAttribute("sessionUser");
        return "frontpages/frontmain";
    }

	@RequestMapping("main")
	public String main(Model model,SysUser sysUser,HttpSession session){
		sysUser = (SysUser) session.getAttribute("sessionUser");
		List<SysMenu> sysMenu = sysMenuService.getTopMenu(sysUser);
		model.addAttribute("topMenu",sysMenu);
		return "main";
	}
	@RequestMapping("showleftmenu")
	public String showleftmenu(Model model,SysUser sysUser,HttpSession session,String menuid){
		sysUser = (SysUser) session.getAttribute("sessionUser");
		List<SysMenu> topMenu = sysMenuService.getTopMenu(sysUser);
		model.addAttribute("topMenu",topMenu);
		List<SysMenu> leftMenu = sysMenuService.getLeftMenu(menuid,sysUser);
		model.addAttribute("leftMenu",leftMenu);
		model.addAttribute("navid",menuid);
        return "showleftmenu";
    }
	@RequestMapping("showiframepic")
	public String showiframepic(){

		return "iframepic";
	}
}
